package cn.cjxy.springmvcdemo2.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

@Controller
public class DownloadController {
	@RequestMapping("/download")
	public void download(String filename, HttpServletRequest req, HttpServletResponse resp) throws Exception{
		//1.获取输入流
		//1.1.获取文件在服务器的绝对路径  文件所存的位置  在tomcat中
		String parentPath = req.getServletContext().getRealPath("/download");
		File file = new File(parentPath, filename);
		if(file.exists()){
            //输入流读取文件
			FileInputStream in = new FileInputStream(file);

			//2.获取输出流
			//2.1.设置文件下载的名字  -- 附件表示做下载或上传操作，浏览器就不会将文件的内容直接显示出来了
			resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
			//2.2.获取输出流
			ServletOutputStream out = resp.getOutputStream();

			//3.实现下载
			IOUtils.copy(in, out);
			//关流，释放资源
			out.close();
			in.close();
		}
	}
}